package top.shaozuo.study.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import lombok.extern.slf4j.Slf4j;
import top.shaozuo.study.mybatis.mapper.CoffeeMapper;
import top.shaozuo.study.mybatis.model.Coffee;

@SpringBootApplication
@Slf4j
public class MybatisDemoApplication implements ApplicationRunner {
	@Autowired
	private CoffeeMapper coffeeMapper;

	@Autowired
	private SqlSessionFactory sqlSessionFactory;

	public static void main(String[] args) {
		SpringApplication.run(MybatisDemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		log.info(sqlSessionFactory.toString());
		Coffee c = Coffee.builder().name("espresso").price(Money.of(CurrencyUnit.of("CNY"), 20.0))
		        .build();
		int count = coffeeMapper.save(c);
		log.info("Save {} Coffee: {}", count, c);

		c = Coffee.builder().name("latte").price(Money.of(CurrencyUnit.of("CNY"), 25.0)).build();
		count = coffeeMapper.save(c);
		log.info("Save {} Coffee: {}", count, c);

		c = coffeeMapper.findById(c.getId());
		log.info("Find Coffee: {}", c);
		try (SqlSession session = sqlSessionFactory.openSession()) {
			CoffeeMapper mapper = session.getMapper(CoffeeMapper.class);
			log.info("mapper == coffeeMapper : {}", mapper == coffeeMapper);
			log.info("{} : {}", mapper, coffeeMapper);
			mapper.findById(c.getId());
		}
	}
}
